import { Component, ViewChild, OnInit } from '@angular/core';
import { PagerComponent } from '../../component/pager/pager.component';
import { ModalService } from '../../component/modal/modal.service';
import { MessageBoxResult } from '../../component/modal/messageBoxResult';
import { UserService, UserQueryParameter } from '../../service/user.service';
import { Toastr } from '../../common/toastr';
import { User } from '../../domain/user';
import { NavbarService } from '../../component/navbar/navbar.service';

@Component({
    templateUrl: 'app/page/user/user.component.html',
    providers: [UserService]
})
export class UserComponent implements OnInit {
    private title: string = "会员管理";
    private subTitle: string = "管理会员信息";
    private queryParams: UserQueryParameter = {
        currentPage: 1,
        pageSize: 10,
        userNick: "",
        phone: ""
    };
    private userList: User[];

    @ViewChild(PagerComponent)
    private pager: PagerComponent;

    constructor(
        private userSvr: UserService,
        private modal: ModalService
    ) { }

    async ngOnInit() {
        this.getUserList();

        this.pager.OnPageIndexChanged = (pageIndex: number) => {
            this.queryParams.currentPage = pageIndex;
            this.getUserList();
        }
    }

    async getUserList() {
        try {
            let r = await this.userSvr.GetUserList(this.queryParams);
            this.userList = r.list;
            this.pager.Load(r.count);
        } catch (error) {
            Toastr.Error(error);
        }
    }

    goUserInfo(id: number) {
        NavbarService.Current.Navigate(['/main/user', id]);
    }

    async enable(user: User) {
        try {
            let r = await this.modal.Show("提示信息", "是否要启用用户【" + user.userNick + "】？");
            if (r == MessageBoxResult.Ok) {
                await this.userSvr.EnableUser(user.userId);
                Toastr.Success("操作成功！");
                this.getUserList();
            }
        } catch (error) {
            Toastr.Error(error);
        }
    }

    async disable(user: User) {
        try {
            let r = await this.modal.Show("提示信息", "是否要禁用用户【" + user.userNick + "】？");
            if (r == MessageBoxResult.Ok) {
                await this.userSvr.DisableUser(user.userId);
                Toastr.Success("操作成功！");
                this.getUserList();
            }
        } catch (error) {
            Toastr.Error(error);
        }
    }
}